package com.ellfors.common.utils

import android.content.Context
import com.google.gson.GsonBuilder
import com.google.gson.reflect.TypeToken
import java.io.BufferedReader
import java.io.File
import java.io.FileInputStream
import java.io.IOException
import java.io.InputStreamReader
import java.lang.reflect.Type

/**
 * JsonUtil
 * 2021-04-30 16:01
 */
object JsonUtil {

    private val _gson by lazy {
        //禁用Html转义
        GsonBuilder().disableHtmlEscaping().create()
    }

    fun <T> json2Obj(json: String?, type: Class<T>?): T? {
        if (json.isNullOrEmpty() || type == null) {
            return null
        }
        return _gson.fromJson(json, type)
    }

    fun <T> json2Obj(json: String?, type: Type?): T? {
        if (json.isNullOrEmpty() || type == null) {
            return null
        }
        return _gson.fromJson(json, type)
    }

    fun <T> json2List(json: String?, clazz: Class<T>): ArrayList<T> {
        if (json.isNullOrEmpty()) {
            return arrayListOf()
        }
        val typeToken = TypeToken.getParameterized(ArrayList::class.java, clazz).type
        return _gson.fromJson(json, typeToken)
    }

    fun obj2Json(src: Any?): String {
        src ?: return ""
        return _gson.toJson(src)
    }

    fun getSDCardJson(filePath: String?): String? {
        if (filePath.isNullOrEmpty()) {
            return null
        }
        val file = File(filePath)
        val stringBuilder = StringBuilder()
        try {
            FileInputStream(file).use { inputStream ->
                InputStreamReader(inputStream, "UTF-8").use { reader ->
                    reader.forEachLine { line ->
                        stringBuilder.append(line).appendLine()
                    }
                }
            }
        } catch (e: IOException) {
            e.printStackTrace()
        }
        return stringBuilder.toString()
    }

    fun getAssetsJson(context: Context, fileName: String?): String? {
        if (fileName.isNullOrEmpty()) {
            return null
        }
        val stringBuilder = StringBuilder()
        try {
            context.assets.open(fileName).use { inputStream ->
                BufferedReader(InputStreamReader(inputStream, "utf-8")).use { reader ->
                    reader.forEachLine { line ->
                        stringBuilder.append(line).appendLine()
                    }
                }
            }
        } catch (e: IOException) {
            e.printStackTrace()
        }
        return stringBuilder.toString()
    }
}